package com.scalar.chiptrack.adaptor.wipfed;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.ScalarException;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Part;
import javax.mail.Header;
import javax.mail.Address;

import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Date;
import java.util.Enumeration;

/**
 * Created by IntelliJ IDEA.
 * User: ChandraSekhar.M
 * Date: Mar 26, 2007
 * Time: 12:13:14 PM
 */
public class WipFedAdaptor extends JobHandler implements AdaptorConstants
{
    private static final String HOST                    = "mail.scalarsoft.com";

    public static final String FILE_NAME_WIP_STATUS 	= "WipFed_Daily_Wip";
    public static final String FILE_NAME_CYPRESS_WIP 	= "SPECT_LIN_WIP";
    public static final String FILE_NAME_SLI_WIP_STATUS = "SLI_WIP";
    public static final String FILE_NAME_SHIP_STATUS    = "DAILY_SHIPS";
    public static final String ADAPTOR_NAME             = "WIPFED_WIP";
    private static final String SUBJECT_WIP             = "SLI REPORT - WIPFED2MP";
    private static final String SUBJECT_SLI_WIP         = "SLI WIP Report";
    private static final String SUBJECT_CYPRESS_WIP     = "Spectra Linear Wip Report";
    private static final String SUBJECT_SHIP            = "ScalarSoft Daily Ships";
    private static final String FROM_ADDRESS            = "jjp@cypress.com";

    private Logger m_adaptorLogger      = null;
    private String m_dataOutputDir            = null;
    private String m_username           = "chiptrac_spectra@scalarsoft.com";
    private String m_password           = "ontrack20";
    private int    m_adaptor_id     = -1;
    
    public WipFedAdaptor() throws Exception
    {
        try
        {   m_dataOutputDir = ConfigManager.getWipFedSheetDirectory();
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );

            m_adaptorLogger = AdaptorUtils.getAdaptorLogger( m_dataOutputDir, "WIPFED" );
            AdaptorUtils.setLogger( m_adaptorLogger );
        }
        catch (ScalarException se)
        {
            System.out.println("ERROR!! ERROR!! ERROR!! Could not create get the WipFed Adaptor output directory/logger, Exception: " + se);
            throw se;
        }
    }

    //Main Method
    public static void main(String[] args) throws Exception
    {
        new WipFedAdaptor().execute();
    }

     /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {
        try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);

            //To prints the Version Information
            AdaptorUtils.printHeader("WIPFED", CONSTANT_ADAPTOR );

            //Removes the Old Records
            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );
            // Step 3
            //Retrive All the Messages
            Message[] messages = AdaptorUtils.getAllPOP3InboxMessages( HOST, m_username, m_password);
            // Step 4
            // Retrieve & Saves the latest message
            //AdaptorUtils.readLatestMessage( m_adaptor_id, messages, SUBJECT_WIP,    m_dataOutputDir, FILE_EXTN_ZIP );
            AdaptorUtils.readLatestMessage( m_adaptor_id, messages, SUBJECT_SLI_WIP,  m_dataOutputDir, FILE_EXTN_XLS, null );
            //AdaptorUtils.fileUnZipping(null, m_dataOutputDir, FILE_EXTN_CSV);


            ////This is Only For Scalar Daily Ships Mail
            readLatestMessage( m_adaptor_id, messages, SUBJECT_SHIP,  m_dataOutputDir, FILE_EXTN_CSV, null );

            readLatestWipMessage( m_adaptor_id, messages, SUBJECT_CYPRESS_WIP,  m_dataOutputDir, FILE_EXTN_CSV, null );

        }
        catch (Exception e)
        {
            AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id);
            System.out.println("Exception while trying to connect and read data from " + HOST +" site: " + e);
            log("Exception while trying to connect and read data from " + HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }

    private void readLatestMessage( int m_adaptor_id, Message[] message, String subject, String outputDir, String fileType, String appendFileName ) throws Exception
    {
        Message wipMessage  = null;
        if ( message == null || message.length == 0 )
        {
            return;
        }

        /*To download Wip sheet */
        for (int i = 0; i < message.length; i++)
        {
            //To get the only  : WIP Report with subject
			if ( message[i].getSubject().startsWith( subject ) || message[i].getSubject().endsWith( subject ) || message[i].getSubject().indexOf(subject) != -1 )
            {

                if ( wipMessage == null )
                {
                    wipMessage = message[i];
                }
                else
                {
                    java.util.Date date2 = null;
                    java.util.Date date1 = null;
                    Enumeration e = wipMessage.getAllHeaders();
                    while ( e.hasMoreElements() )
                    {
                        Header h = (Header)e.nextElement();

                        if ("Date".equalsIgnoreCase(h.getName() ) )
                        {
                            //date1 = StringUtils.format( StringUtils.formatDate(h.getValue().substring(0, 11), "dd MMM yyyy", "MM/dd/yyyy" )  );
                            date1 = StringUtils.format(h.getValue(), "dd MMM yyyy zzz HH:mm:ss");
                        }
                    }

                    Enumeration e1 = message[i].getAllHeaders();
                    while ( e1.hasMoreElements() )
                    {
                        Header h = (Header)e1.nextElement();
                        if ("Date".equalsIgnoreCase(h.getName() ) )
                        {
                              //date2 = StringUtils.format( StringUtils.formatDate(h.getValue().substring(0, 11), "dd MMM yyyy", "MM/dd/yyyy" )  );
                            date2 = StringUtils.format(h.getValue(), "dd MMM yyyy zzz HH:mm:ss");
                        }
                    }

                    if (date1 != null && date2 != null)
                    {
                        if (date2.compareTo(date1) > 0)
                        {
                            wipMessage = message[i];
                        }
                    }
                }
            }
        }

        // To process the Message and download the files
        if ( wipMessage != null )
        {
            java.util.Date maxDate = null;
            Enumeration e = wipMessage.getAllHeaders();
            while ( e.hasMoreElements() )
            {
                Header h = (Header)e.nextElement();

                if ("Date".equalsIgnoreCase( h.getName() ) )
                {
                    //maxDate = StringUtils.format( StringUtils.formatDate(h.getValue().substring(0, 11), "dd MMM yyyy", "MM/dd/yyyy" )  );
                    maxDate = StringUtils.format(h.getValue(), "dd MMM yyyy zzz HH:mm:ss");
                }
            }

            //System.out.println("maxDate = " + maxDate);

            Multipart mp = (Multipart) wipMessage.getContent();
            
            String fileName = null;
            InputStream  inputStream = null;
            for ( int i = 0; i < mp.getCount(); i++ )
            {
                Part part = mp.getBodyPart(i);
                                
                if ( part.getFileName() != null )
                {

                    fileName =  part.getFileName().substring( 0 , part.getFileName().lastIndexOf(".") );


                    inputStream = part.getInputStream();

                    if ( fileName != null )
                    {
                        fileName = fileName.replaceAll("-", "_").toUpperCase();

                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , fileName, fileType, StringUtils.formatDateToString( maxDate, "MM/dd/yyyy HH:mm:ss") ) ;
                        }

                        if ( appendFileName != null )
                        {
                            fileName = appendFileName +"_" + fileName;
                        }

                        log("\tDownloding "+subject+"................. ");
                        System.out.println("\tDownloding "+subject+"................. ");

                        AdaptorUtils.saveAsBinaryFile( new BufferedInputStream(inputStream), outputDir, fileName, fileType, true /* append time stamp */);
                        fileName = null;
                        System.out.println("Done.\n"  );
                    }
                }
            }
            //AdaptorUtils.downLoadMessage( m_adaptor_id, wipMessage, maxDate, subject, outputDir, fileType, appendFileName );
            wipMessage = null;
        }
        else
        {
             log("\n\n****The Requested File was not found in INBOX***\n");
             System.out.println("\n\n****The Requested File was not found in INBOX***\n");
        }
    }


    private void readLatestWipMessage( int m_adaptor_id, Message[] message, String subject, String outputDir, String fileType, String appendFileName ) throws Exception
    {
        Message wipMessage  = null;
        if ( message == null || message.length == 0 )
        {
            return;
        }

        /*To download Wip sheet */
        for (int i = 0; i < message.length; i++)
        {               
            //To get the only  : WIP Report with subject
			if ( message[i].getSubject().startsWith( subject ) || message[i].getSubject().endsWith( subject ) || message[i].getSubject().indexOf(subject) != -1 )
            {
                Address address[] = message[i].getFrom();

                for( int j = 0; j < address.length ; j++ )
                {
                    //to get the only from address
                    if( address[j].toString() != null && FROM_ADDRESS.equalsIgnoreCase( address[j].toString() ) )
                    {
                        log( "From  :=  " + address[j].toString() );
                         if (wipMessage == null)
                        {
                            wipMessage = message[i];
                            
                        }
                        else
                        {
                            java.util.Date date2 = null;
                            java.util.Date date1 = null;
                            Enumeration e = wipMessage.getAllHeaders();
                            while ( e.hasMoreElements() )
                            {
                                Header h = (Header)e.nextElement();

                                if ("Date".equalsIgnoreCase(h.getName() ) )
                                {
                                    //date1 = StringUtils.format( StringUtils.formatDate(h.getValue().substring(0, 11), "dd MMM yyyy", "MM/dd/yyyy HH:mm:ss" )  );
                                    date1 = StringUtils.format(h.getValue(), "dd MMM yyyy zzz HH:mm:ss");
                                }
                            }

                            Enumeration e1 = message[i].getAllHeaders();
                            while ( e1.hasMoreElements() )
                            {
                                Header h = (Header)e1.nextElement();
                                if ("Date".equalsIgnoreCase(h.getName() ) )
                                {
                                    //date2 = StringUtils.format( StringUtils.formatDate(h.getValue().substring(0, 11), "dd MMM yyyy", "MM/dd/yyyy" )  );
                                    date2 = StringUtils.format(h.getValue(), "dd MMM yyyy zzz HH:mm:ss");
                                }
                            }

                            if (date1 != null && date2 != null)
                            {
                                if (date2.compareTo(date1) > 0)
                                {
                                    wipMessage = message[i];
                                }
                            }
                        }
                    }
                }
            }
        }

        // To process the Message and download the files
        if ( wipMessage != null )
        {
            java.util.Date maxDate = null;
            Enumeration e = wipMessage.getAllHeaders();
            while ( e.hasMoreElements() )
            {
                Header h = (Header)e.nextElement();

                if ("Date".equalsIgnoreCase( h.getName() ) )
                {
                    //maxDate = StringUtils.format( StringUtils.formatDate(h.getValue().substring(0, 11), "dd MMM yyyy", "MM/dd/yyyy" )  );
                    maxDate = StringUtils.format(h.getValue(), "dd MMM yyyy zzz HH:mm:ss");
                }
            }

            Multipart mp = (Multipart) wipMessage.getContent();

            String fileName = null;
            InputStream  inputStream = null;
            for ( int i = 0; i < mp.getCount(); i++ )
            {
                Part part = mp.getBodyPart(i);

                if ( part.getFileName() != null )
                {
                    fileName =  part.getFileName().substring( 0 , part.getFileName().lastIndexOf(".") );

                    inputStream = part.getInputStream();

                    if ( fileName != null )
                    {
                        fileName = fileName.replaceAll("-", "_").toUpperCase();

                        if ( m_adaptor_id > 0 )
                        {                               
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , fileName, fileType, StringUtils.formatDateToString( maxDate, "MM/dd/yyyy HH:mm:ss") ) ;
                        }

                        if ( appendFileName != null )
                        {
                            fileName = appendFileName +"_" + fileName;
                        }

                        log("\tDownloding "+subject+"................. ");
                        System.out.println("\tDownloding "+subject+"................. ");

                        AdaptorUtils.saveAsBinaryFile( new BufferedInputStream(inputStream), outputDir, fileName, fileType, true /* append time stamp */);
                        fileName = null;
                        System.out.println("Done.\n"  );
                    }
                }
            }
            
            wipMessage = null;
        }
        else
        {
             log("\n\n****The Requested File was not found in INBOX***\n");
             System.out.println("\n\n****The Requested File was not found in INBOX***\n");
        }
    }
    private void log(String message)
    {
        if (message == null) return;

        if (m_adaptorLogger != null)
        {
            synchronized (m_adaptorLogger)
            {
                m_adaptorLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }
}